package com.aop.processor;

import com.aop.bean.Person;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author: tgy
 * @Date: 2020-08-10 09:27
 */
public class PersonBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        if (bean instanceof Person){


//            jdk proxy
//           return Proxy.newProxyInstance(PersonBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
//                @Override
//                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//
//                    System.out.println(method.getName() + "before");
//
//                    Object invoke = method.invoke(bean, args);
//
//                    System.out.println(method.getName() + "after");
//
//                    return invoke;
//                }
//            });

            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(bean.getClass());
            enhancer.setClassLoader(PersonBeanPostProcessor.class.getClassLoader());
            enhancer.setUseCache(false);
            enhancer.setCallback(new MethodInterceptor() {
                @Override
                public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                    System.out.println(method.getName() + "before");
                    Object invoke = method.invoke(bean, objects);
                    System.out.println(method.getName() + "after");
                    return invoke;
                }
            });

            return enhancer.create();
        }

        return bean;
    }
}
